package com.sqx.modules.health.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.mapper.ReceiveMapper;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.vo.SrcDataValue;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/**
 * @Description: 血糖设备数据采集service
 * @Author: gxy
 **/
@Service
public class ReceiveDataServiceImpl implements ReceiveDataService {

    private static Logger logger = LoggerFactory.getLogger(ReceiveDataServiceImpl.class);
    @Autowired
    private IReceiveService receiveService;
    @Autowired
    private ReceiveMapper receiveMapper;
    @Autowired
    private INcgDeviceWatchService deviceWatchService;
    @Autowired
    private IWarningService warningService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IRecordsetService recordsetService;
    @Autowired
    private INcgDeviceWatchService watchService;

    @Autowired
    private IUserService userService;


    /**
     * 处理上报的数据
     *
     * @param srcDatavalue
     * @return
     */
    @Override
    public boolean handleReceivedData(SrcDataValue srcDatavalue) {
        String patientId = UUID.randomUUID().toString();
        String devSN = srcDatavalue.getSerialNumber();
        //String devSN = "19B881791";
        boolean flag = true;

        Integer userId = null;
        Integer doctorid= null;

        NcgDeviceWatch transferDeviceWatch =  watchService.getOne(new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(devSN),"imei", devSN));
        if (null == transferDeviceWatch) {
            flag = false;
            return flag;
        }

        if (StringUtils.isEmpty(transferDeviceWatch.getTransferuid())) {
            userId = Math.toIntExact(transferDeviceWatch.getUid());
            SysUserEntity user = userService.getById(userId);
            if (ObjectUtil.isNotEmpty(user)) {
                doctorid = Math.toIntExact(user.getBelongsDoctor());
            }
            /*if (StringUtils.isEmpty(srcDatavalue.getUser())) {
                doctorid = Integer.parseInt(srcDatavalue.getUser());
            }*/
        } else {
            SysUserEntity transferUser = userService.findByUid(transferDeviceWatch.getTransferuid());
            if (ObjectUtil.isNotEmpty(transferUser)) {
                userId = Math.toIntExact(transferUser.getUserId());
                if (transferUser.getBelongsDoctor() != null && transferUser.getBelongsDoctor() != 0) {
                    doctorid = Math.toIntExact(transferUser.getBelongsDoctor());
                }
                transferDeviceWatch.setTransferuid("");
                watchService.updateById(transferDeviceWatch);
            }
        }

        try {
            Receive receive = new Receive();
            receive.setPatientId(patientId);
            receive.setUid(userId);
            receive.setDoctorid(doctorid);
            String createTime = "20" + srcDatavalue.getYear() + "-" + srcDatavalue.getMonth() + "-" + srcDatavalue.getDay();
            createTime = createTime + " " + srcDatavalue.getHour() + ":" + srcDatavalue.getMinute() + ":00";
            receive.setCreatetime(createTime);
            receive.setVersion(srcDatavalue.getVersion());
            receive.setImei(srcDatavalue.getImsi());
            receive.setDeviceType(srcDatavalue.getDeviceType());
            receive.setDevSN(devSN);
            BigDecimal bigDecimal = new BigDecimal(srcDatavalue.getData3());
            String glucose = bigDecimal.divide(new BigDecimal(18), 2, BigDecimal.ROUND_UP).toString();
            receive.setGlucose(glucose);
            checkWarning(receive);
            boolean result = receiveService.save(receive);
            if (!result) {
                flag = false;
            }

            QueryWrapper<NcgDeviceWatch> wwwrapper = new QueryWrapper<NcgDeviceWatch>()
                    .eq(ObjectUtil.isNotEmpty(devSN),"imei", devSN);
            NcgDeviceWatch deviceWatch =  watchService.getOne(wwwrapper);

            if (deviceWatch.getPositionid() == 1){

                Record record = recordService.getOneByDevSn(devSN, 1);
                if (ObjectUtil.isNotEmpty(record)) {
//                    if (!ObjectUtil.equals(record.getFlag(), 0)) {
//                        record.setId(null);
//                        record.setRecordtime(createTime);
//                    }
                    if (StringUtils.isEmpty(record.getImei())) {
                        record.setImei(devSN);
                    }
                    record.setRecordtime(createTime);
                    record.setGlucose(bigDecimal.divide(new BigDecimal(18), 2, BigDecimal.ROUND_UP));
                    record.setFlag(1);
                    recordService.saveOrUpdate(record);

                    Recordset recordset = recordsetService.getLast(devSN);
                    recordset.setStatus(1);
                    recordset.setEnddate(LocalDateTime.now());
                    recordsetService.saveOrUpdate(recordset);

                    LambdaUpdateWrapper<NcgDeviceWatch> wrapper = new LambdaUpdateWrapper<NcgDeviceWatch>()
                            .set(NcgDeviceWatch::getDoctorid, null)
                            .set(NcgDeviceWatch::getUid, null)
                            .set(NcgDeviceWatch::getStatus, 3)
                            .eq(ObjectUtil.isNotEmpty(devSN), NcgDeviceWatch::getImei, devSN);
                    watchService.update(wrapper);
                }

            }else {

                Record records = new Record();
                /*records.setUid(deviceWatch.getUid());
                records.setDoctorid(deviceWatch.getDoctorid());*/
                records.setUid((long) userId);

                if (doctorid != null) {
                    records.setDoctorid((long) doctorid);
                }

                records.setImei(devSN);
                records.setType(1);
                records.setRecordtime(createTime);
                records.setGlucose(bigDecimal.divide(new BigDecimal(18), 2, BigDecimal.ROUND_UP));
                records.setFlag(1);
                recordService.save(records);

                Recordset recordset = new Recordset();
                recordset.setImei(devSN);
                recordset.setStartdate(LocalDateTime.now());
                recordset.setEnddate(LocalDateTime.now());
                /*recordset.setUid(deviceWatch.getUid());
                recordset.setDocid(deviceWatch.getDoctorid());*/
                recordset.setUid((long) userId);

                if (doctorid != null) {
                    recordset.setDocid((long) doctorid);
                }

                recordset.setStatus(1);
                recordset.setDevicetype(1);
                recordsetService.save(recordset);
//                records.setShrink(Integer.parseInt(srcDatavalue.getData1()));
//                records.setDiastole(Integer.parseInt(srcDatavalue.getData2()));
//                records.setPulse(Integer.parseInt(srcDatavalue.getData3()));
//                records.setRate(Integer.parseInt(srcDatavalue.getData3()));
//                records.setSampleDate(LocalDateTime.parse(createTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

        } catch (Exception e) {
            logger.error("GPRS血糖设备血糖上传异常", e);
            flag = false;
        }
        return flag;
    }

    /**
     * 验证血糖数据 是否处于健康范围
     * 一个为空腹血糖，一个为餐后两小时血糖。空腹血糖为3.9-6.0mmol/L或者70-108mg/dL，为血糖正常值。餐后两小时血糖＜7.7mmol/L或139mg/dL，为血糖正常值。
     * 空腹血糖≥7.0mmol/L或126mg/dL，应当考虑糖尿病。其次，餐后两小时血糖≥11.1mmol/L或200mg/dL，应当考虑糖尿病。
     * 对于空腹血糖在6.0-7.0mmol/L之间，称之为空腹血糖调节受损。对于餐后两小时血糖在7.8-11.0mmol/L之间，称之为糖耐量异常。
     *
     * @param receive
     */
    private void checkWarning(Receive receive) {
        Warning warning = new Warning();
        if (receive.getGlucose() != null) {
            if (ObjectUtil.equals(new BigDecimal(receive.getGlucose()).compareTo(new BigDecimal(11.1)), 1) || ObjectUtil.equals(new BigDecimal(receive.getGlucose()).compareTo(new BigDecimal(11.1)), 0)) {
                warning.setWarningType("血糖过高");
                saveData(receive, warning);
            } else if (ObjectUtil.equals(new BigDecimal(receive.getGlucose()).compareTo(new BigDecimal(7.8)), 1) && ObjectUtil.equals(new BigDecimal(receive.getGlucose()).compareTo(new BigDecimal(11.0)), -1)) {
                warning.setWarningType("糖耐量异常");
                saveData(receive, warning);
            }
        }
    }

    private void saveData(Receive receive, Warning warning) {
        // 根据 IMEI 获取绑定的用户
        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<>();
        wrapper.eq("imei", receive.getImei());
        NcgDeviceWatch one = deviceWatchService.getOne(wrapper);
        warning.setId(UUID.randomUUID().toString().replace("-", ""));
        //具有转换功能的对象
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // String 转为 LocalDateTime
        LocalDateTime parse = LocalDateTime.parse(receive.getCreatetime(), df);
        warning.setCreatetime(parse);
        warning.setImei(receive.getImei());
        warning.setDevSN(receive.getDevSN());
        warning.setUid(one != null ? one.getUid() : null);
        warning.setSource("爱奥乐血糖仪");
        warningService.save(warning);
    }
}
	
	


